#pragma once

#ifndef TCLOSURESET_H
#define TCLOSURESET_H

#include <unordered_map>
#include <mutex>

template<typename T>
class TTaskClosureSet
{
public:
    typedef std::unordered_map<T,char>	Container;/* 无序map在查找性能更好,value不使用仅占位 */
    TTaskClosureSet():m_containerPtr(nullptr){}

    ~TTaskClosureSet()
    {
        destroy();
    }

    bool add(T pClosure)
    {
        Container * container = getSets();
        if(container)
        {
            std::lock_guard<std::mutex> lock(m_mutex);
            (*container)[pClosure] = 0;
            return true;
        }

        return false;
    }

    bool remove(T pClosure)
    {
        Container * container = getSets();
        if(container)
        {
            std::lock_guard<std::mutex> lock(m_mutex);
            container->erase(pClosure);
            return true;
        }

        return false;
    }

    bool contains(T pClosure)
    {
        Container * container = getSets();
        if(container)
        {
            std::lock_guard<std::mutex> lock(m_mutex);
            return container->find(pClosure) != container->end();
        }

        return false;
    }

    void destroy()
    {
        std::lock_guard<std::mutex> lock(m_mutex);

        if(m_containerPtr)
        {
            m_containerPtr->clear();
            delete m_containerPtr;
            m_containerPtr = NULL;
        }
    }

    Container * getSets()
    {
        if(m_containerPtr) return m_containerPtr;

        std::lock_guard<std::mutex> lock(m_mutex);

        return m_containerPtr = new Container;
    }
private:
    Container * m_containerPtr;
    std::mutex m_mutex;
};

#endif // TCLOSURESET_H
